package helen.core.net;

import android.content.Context;


import java.util.ArrayList;
import java.util.List;

import helen.core.iinterface.NetRequestTask;

/**
 * 用于以处理网络请求队列的类
 * Created by cssnote on 2015/11/10.
 */
public class NetTaskManagerFIFO {
    private List<NetRequestTask> waitList;
    private List<NetRequestTask> dealedList;
    private List<TaskInfoUtil> dealInfoList;
    private List<TaskInfoUtil> infoList;
    private NetRequestTask execTask;
    private Thread looper;
    private boolean isRun = false;
    private boolean isParse = false;

    public NetTaskManagerFIFO() {
        waitList = new ArrayList<>();
        dealedList = new ArrayList<>();
        dealedList = new ArrayList<>();
        dealInfoList = new ArrayList<>();
    }

    public void addTask(NetRequestTask task,TaskInfoUtil info) {
        waitList.add(task);
        infoList.add(info);
        if (!isRun){
            startLooper();
        }
    }

    public boolean isrun(){
        return isRun;
    }

    public void runNow(){
        if(!isRun) {
            isParse = false;
            startLooper();
        }
    }

    public void parse(){
        isParse = true;
    }

    public boolean isParse(){
        return isParse;
    }

    public void resume(){
        if(!isRun) {
            isParse = false;
            startLooper();
        }
    }

    private void startLooper() {
        looper = new Thread() {
            @Override
            public void run() {
                super.run();
                isRun = true;
                while (waitList.size() != 0&&dealedList.size()!=0) {
                    if (isParse) {
                        break;
                    }
                    TaskInfoUtil infoUtil = infoList.remove(0);
                    execTask = waitList.remove(0);
                    execTask.beforeRequest(infoUtil.context);
                    execTask.request(infoUtil.context, infoUtil.handler, infoUtil.messageWhat, infoUtil.DataTag);
                    execTask.afterRequest(infoUtil.context);
                    dealedList.add(execTask);
                    dealInfoList.add(infoUtil);
                }
                isRun = false;
            }
        };
    }


}
